package org.qpcr.community.auth.web.excel;

import lombok.Getter;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.validator.ValidatorUtils;
import org.qpcr.community.auth.entity.OrganizationEntity;
import org.qpcr.community.auth.entity.RoleEntity;
import org.qpcr.community.auth.entity.UserDetail;
import org.qpcr.community.io.excel.AbstractImporter;
import org.qpcr.community.io.excel.ImportHelper;
import org.qpcr.community.io.file.FileManager;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 用户导入.
 *
 * @author yanss 2024/6/13
 * @since 2.1
 */
public class UserExcelImporter extends AbstractImporter<UserExcelInfo> {

    @Getter
    private final List<UserDetail> userList;
    @Getter
    private final List<OrganizationEntity> organizationEntityList;
    @Getter
    private final List<RoleEntity> roleEntityList;

    private final Authentication auth;

    public UserExcelImporter(FileManager fileManager,
                             WebClient client,
                             List<UserDetail> userList,
                             List<OrganizationEntity> organizationEntityList,
                             List<RoleEntity> roleEntityList, Authentication auth) {
        super(fileManager, client);
        this.userList = userList;
        this.organizationEntityList = organizationEntityList;
        this.roleEntityList = roleEntityList;
        this.auth = auth;
    }

    @Override
    protected Mono<Void> handleData(Flux<UserExcelInfo> data) {
        return data
            .doOnNext(ValidatorUtils::tryValidate)
            .map(testItemExcelInfo -> testItemExcelInfo.initTestItemInstance(userList, organizationEntityList, roleEntityList, auth))
            .then();
    }

    @Override
    protected UserExcelInfo newInstance() {
        return new UserExcelInfo();
    }

    @Override
    protected void customImport(ImportHelper<UserExcelInfo> helper) {
        helper.fallbackSingle(true);
    }
}
